<template>
  <v-app>
    <!-- 顶部应用栏 -->
    <v-app-bar :elevation="1" app>
      <v-app-bar-nav-icon @click="toggleDrawer" v-if="isMobile"></v-app-bar-nav-icon>

      <v-toolbar-title>
        {{ $t('common.schoolAttendanceSystem') || 'Newton校园考勤系统' }}
      </v-toolbar-title>

      <v-spacer></v-spacer>

      <!-- 语言切换 -->
      <v-menu>
        <template v-slot:activator="{ props }">
          <v-btn icon v-bind="props">
            <v-icon>mdi-translate</v-icon>
          </v-btn>
        </template>
        <v-list>
          <v-list-item
            v-for="lang in languages"
            :key="lang.code"
            @click="changeLanguage(lang.code)"
          >
            <v-list-item-title>{{ lang.name }}</v-list-item-title>
          </v-list-item>
        </v-list>
      </v-menu>

      <!-- 用户菜单 -->
      <v-menu>
        <template v-slot:activator="{ props }">
          <v-btn icon v-bind="props">
            <v-avatar size="32">
              <v-img :src="avatarUrl" :alt="authStore.userName"></v-img>
            </v-avatar>
          </v-btn>
        </template>
        <v-list>
          <v-list-item @click="goToProfile">
            <v-list-item-title>
              <v-icon class="me-2">mdi-account</v-icon>
              {{ $t('common.profile') }}
            </v-list-item-title>
          </v-list-item>
          <v-list-item @click="logout">
            <v-list-item-title>
              <v-icon class="me-2">mdi-logout</v-icon>
              {{ $t('common.logout') }}
            </v-list-item-title>
          </v-list-item>
        </v-list>
      </v-menu>
    </v-app-bar>

    <!-- 侧边导航栏（位于顶部导航下方） -->
    <v-navigation-drawer
      v-model="drawer"
      :temporary="isMobile"
      :permanent="!isMobile"
      location="start"
      app
      width="240"
      class="sidebar-below-header"
    >
      <v-list density="compact" nav>
        <v-list-item
          v-for="item in navigationItems"
          :key="item.title"
          :prepend-icon="item.icon"
          :title="$t(item.title)"
          :to="item.to"
          :value="item.title"
        ></v-list-item>
      </v-list>
    </v-navigation-drawer>

    <!-- 主内容区域 -->
    <v-main >
      <v-container fluid>
        <router-view />
      </v-container>
    </v-main>

    <!-- 全局通知 -->
    <v-snackbar
      v-model="notification.show"
      :color="notification.color"
      :timeout="4000"
      location="top right"
    >
      {{ notification.message }}
      <template v-slot:actions>
        <v-btn
          color="white"
          variant="text"
          @click="notification.show = false"
        >
          关闭
        </v-btn>
      </template>
    </v-snackbar>
  </v-app>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/stores/auth'
import { useAfterSchoolStore } from '@/stores/afterSchool'
import { useStudentsStore } from '@/stores/students'
import { useDisplay } from 'vuetify'

const router = useRouter()
const { locale, t } = useI18n()
const authStore = useAuthStore()
const afterSchoolStore = useAfterSchoolStore()
const studentsStore = useStudentsStore()
const { mobile } = useDisplay()

// 响应式数据
const drawer = ref(true)
const isMobile = ref(false)
const notification = ref({
  show: false,
  message: '',
  color: 'info'
})

// 语言选项
const languages = [
  { code: 'zh', name: '中文' },
  { code: 'en', name: 'English' }
]

// 计算属性
const avatarUrl = computed(() => {
  return `https://api.dicebear.com/7.x/initials/svg?seed=${authStore.userName}`
})

const userRoleText = computed(() => {
  const roleMap = {
    admin: t('user.admin'),
    teacher: t('user.teacher'),
    driver: t('user.driver')
  }
  return roleMap[authStore.userRole] || authStore.userRole
})

const navigationItems = computed(() => {
  const role = authStore.userRole
  
  const allItems = {
    admin: [
      { title: 'nav.dashboard', icon: 'mdi-view-dashboard', to: '/admin/dashboard' },
      { title: 'nav.classManagement', icon: 'mdi-school', to: '/admin/classes' },
      { title: 'nav.teacherManagement', icon: 'mdi-account-tie', to: '/admin/teachers' },
      { title: 'nav.userManagement', icon: 'mdi-account-cog', to: '/admin/users' },
      { title: 'nav.attendanceSettings', icon: 'mdi-clock-outline', to: '/admin/attendance-settings' },
      { title: 'nav.afterSchoolClassManagement', icon: 'mdi-book-open-variant', to: '/admin/after-school-classes' },
    ],
    teacher: [
      { title: 'nav.dashboard', icon: 'mdi-view-dashboard', to: '/teacher/dashboard' },
      { title: 'nav.arrivalManagement', icon: 'mdi-clock-in', to: '/teacher/arrival' },
      { title: 'nav.departureManagement', icon: 'mdi-clock-out', to: '/teacher/departure' }
    ],
    driver: [
      { title: 'nav.departureManagement', icon: 'mdi-clock-out', to: '/driver/departure' }
    ],
    after_school_teacher: [
      { title: 'nav.arrivalManagement', icon: 'mdi-clock-in', to: '/after-school/arrival' }
    ]
  }
  
  return allItems[role] || []
})

// 方法
const updateMobileState = () => {
  isMobile.value = mobile.value
  if (mobile.value) {
    drawer.value = false
  } else {
    drawer.value = true
  }
}

const toggleDrawer = () => {
  drawer.value = !drawer.value
}

const changeLanguage = (langCode) => {
  locale.value = langCode
  localStorage.setItem('language', langCode)
}

const goToProfile = () => {
  router.push('/profile')
}

const logout = async () => {
  authStore.logout()
  router.push('/login')
  showNotification('已退出登录', 'info')
}

const showNotification = (message, color = 'info') => {
  notification.value = {
    show: true,
    message,
    color
  }
}

// 生命周期
onMounted(() => {
  // 恢复语言设置
  const savedLang = localStorage.getItem('language')
  if (savedLang) {
    locale.value = savedLang
  }
  
  // 初始化移动端状态
  updateMobileState()
  
  // 监听屏幕尺寸变化
  window.addEventListener('resize', updateMobileState)
  
  // 初始化WebSocket监听器
  if (authStore.isAuthenticated) {
    // 初始化课后托班WebSocket监听
    afterSchoolStore.initSocketListeners()
    // 初始化学生状态WebSocket监听
    studentsStore.initSocketListeners()
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', updateMobileState)
})

// 全局错误处理（可以通过provide/inject传递给子组件）
window.showNotification = showNotification
</script>

<style scoped>

:deep(.v-app-bar) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.12);
  position: fixed !important;
  top: 0 !important;
  z-index: 1006 !important;
}

.sidebar-below-header {
  border-right: 1px solid rgba(0, 0, 0, 0.12);
  position: fixed !important;
  top: 64px !important; /* 位于应用栏下方 */
  height: calc(100vh - 64px) !important; /* 减去应用栏高度 */
  z-index: 1005 !important;
}

.v-main {
  background-color: #eeeeee;
  padding-top: 0 !important; /* 移除默认padding */
  margin-top: 64px !important; /* 为固定的应用栏留出空间 */

}

.v-container {
  padding: 16px;
}

/* 移动端样式 */
@media (max-width: 1023px) {
  .sidebar-below-header {
    position: fixed !important;
    top: 64px !important;
    height: calc(100vh - 64px) !important;
  }
  
  .v-main {
    margin-left: 0 !important;
  }
}

/* 桌面端样式 */
@media (min-width: 1024px) {
}

/* 主内容区域优化 */
.v-container {
  max-width: none !important; /* 移除最大宽度限制 */
  padding: 16px 24px; /* 增加左右内边距 */
}

/* 确保内容充分利用可用空间 */
@media (min-width: 1024px) {
  .v-container {
    padding: 24px 32px; /* 桌面端增加更多内边距 */
  }
}
</style>
